/**
 * 店铺授权
 * author:elvis
 */

import React, { useState, useEffect } from "react";
import BuyConfirm from './component/BuyConfirm';
import { Base64 } from 'js-base64';
import { Form, message, Button } from 'antd';
import { find } from 'lodash';
import { useLocation, useNavigate, Navigate } from 'react-router-dom'; 
import { layout1 } from '@/utils/config'
import { getCurrentUser } from '@/utils/authority';
import { stringify } from 'qs';
import { handleAuthorize as handleAuthorizeFunc } from '@/utils/utils.jsx';
import styles from './index.module.less';

const imgData = {
  '1': { src: 'https://imgniu.zhaojiafang.com/tb.png', src_w: 'https://imgniu.zhaojiafang.com/tb_w.png' },
  '2': { src: 'https://imgniu.zhaojiafang.com/tm.png', src_w: 'https://imgniu.zhaojiafang.com/tm_w.png' },
  '3': { src: 'https://imgniu.zhaojiafang.com/jd.png', src_w: 'https://imgniu.zhaojiafang.com/jd_w.png' },
  '4': { src: 'https://imgniu.zhaojiafang.com/pdd.png', src_w: 'https://imgniu.zhaojiafang.com/pdd_w.png' },
  '5': { src: 'https://imgniu.zhaojiafang.com/1688.png', src_w: 'https://imgniu.zhaojiafang.com/1688_w.png' },
  '6': { src: 'https://imgniu.zhaojiafang.com/sn.png', src_w: 'https://imgniu.zhaojiafang.com/sn_w.png' },
  '7': { src: 'https://imgniu.zhaojiafang.com/snlt.png', src_w: 'https://imgniu.zhaojiafang.com/snlt_w.png' },
  '8': { src: 'https://imgniu.zhaojiafang.com/youzan.png', src_w: 'https://imgniu.zhaojiafang.com/youzan_w.png' },
  '9': { src: 'https://imgniu.zhaojiafang.com/hqls.png', src_w: 'https://imgniu.zhaojiafang.com/hqls_w.png' },
  '12': { src: 'https://imgniu.zhaojiafang.com/ks.png', src_w: 'https://imgniu.zhaojiafang.com/ks_w.png' },
  '13': { src: 'https://imgniu.zhaojiafang.com/wph.png', src_w: 'https://imgniu.zhaojiafang.com/wph_w.png' },
}

export default () => {

  const [ id, setId ] = useState(undefined);//当前选中的平台id
  const [ visible2, setVisible2 ] = useState(false);//购买确认弹框
  const [ form ] = Form.useForm();

  const umiLocation = useLocation();

	const navigate = useNavigate();

  const data = [
    { id: 1, src: imgData['1'].src, src_w: imgData['1'].src_w, path: `https://oauth.taobao.com/authorize?response_type=code&client_id=23416550&redirect_uri=http://tb-api.zhaojiafang.com/TopSdk.php&state=${AUTHORIZE_URL}/taobao/callback-callback-` },
    // { id: 2, src: imgData['2'].src, src_w: imgData['2'].src_w },
    { id: 3, src: imgData['3'].src, src_w: imgData['3'].src_w, path: `https://auth.360buy.com/oauth/authorize?response_type=code&client_id=7400F31DF539216DBDA2E06BD5E91C57&redirect_uri=http://threegateway.zhaojiafang.com/jd/callback&state=` },
    // { id: 4, src: imgData['4'].src, src_w: imgData['4'].src_w, path: `https://mms.pinduoduo.com/open.html?response_type=code&client_id=d151e0b2a81042d496d22f70a729a971&redirect_uri=https://www.zhaojiafang.com/pdd.php&state=${AUTHORIZE_URL}/pdd/callback-callback-` },
    // { id: 5, src: imgData['5'].src, src_w: imgData['5'].src_w, path: `https://auth.1688.com/oauth/authorize?client_id=7342795&site=1688&redirect_uri=https://open-tb.zhaojiafang.com/alibaba.php&state=${AUTHORIZE_URL}/alibaba/callback-callback-` },
    // { id: 6, src: imgData['6'].src, src_w: imgData['6'].src_w_w },
    // { id: 7, src: imgData['7'].src, src_w: imgData['7'].src_w },
    // { id: 8, src: imgData['8'].src, src_w: imgData['8'].src_w },
    // { id: 9, src: imgData['9'].src, src_w: imgData['9'].src_w },
    // { id: 12, src: imgData['12'].src, src_w: imgData['12'].src_w, path: `https://s.kwaixiaodian.com/oauth/authorize?appId=ks661466197236322196&redirect_uri=http://threegateway.zhaojiafang.com/ks/callback&scope=merchant_refund,merchant_order,merchant_user,merchant_item&response_type=code&state=` },
    // { id: 0 },
  ]
  
  function handleOk() {
    if(id) {
      if(id == 12) {
        handleAuthorize();
      } else {
        setVisible2(true);
      }
    } else {
      if(id == 0) {//线下店铺
        setVisible1(true);
      } else {
        message.warning('请先选择需要授权的平台！');
      }
    }
  }

  const handleAuthorize = (val={}) => {
    if(id == 4) {//拼多多
      const url = window.location.href;
      const obj = JSON.stringify({
        url,
        userName: getCurrentUser().account,
        uuid: getCurrentUser().uuid,
        ...val,
      })
      const path = find(data, ['id', id]).path;
      const src = `${path}${encodeURIComponent(encodeURIComponent(Base64.encode(obj)))}`;
      window.location.href=src;
    } else if(id == 1 || id == 5) {//淘宝
      const url = window.location.href;
      const obj = JSON.stringify({
        url,
        userName: getCurrentUser().account,
        uuid: getCurrentUser().uuid,
        ...val,
      })
      const path = find(data, ['id', id]).path;
      const src = `${path}${encodeURIComponent(Base64.encode(obj))}`;
      window.location.href=src;
    } else if(id == 3 || id ==12) {//京东和快手
      const url = window.location.href;
      const obj = JSON.stringify({
        url,
        userName: getCurrentUser().account,
        uuid: getCurrentUser().uuid,
        josUrl: `http://${AUTHORIZE_URL}`,
        ...val,
      })
      const path = find(data, ['id', id]).path;
      const src = `${path}${encodeURIComponent(encodeURIComponent(Base64.encode(obj)))}`;
      window.location.href=src;
    }
  }

  const BuyConfirmProps = {
    id: id,
    visible: visible2,
    handleOk(val) {
      handleAuthorize(val);
    },
    handleCancel() {
      setVisible2(false);
    }
  }

  useEffect(() => {
    const userObj  = getCurrentUser();
    if(userObj) {
      handleAuthorizeFunc(umiLocation, navigate);
    }
    //检测是否是授权回调
  }, [])

  const isLogin  = getCurrentUser();

  if(isLogin) {
    return (
      <div className={styles.wrapBox}>
        <div className={styles.continer}>
          <h3 style={{ marginBottom: '24px' }}>店铺授权</h3>
          <Form 
            { ...layout1 } 
            form={form}
            name="authorize-store"
          >
            <Form.Item 
              name="shop_name" 
              label="选择平台"
              extra={<p className='color1'>注：新系统授权对老系统订单无影响，可以放心授权</p>}
            >
              <div className={styles.wrap}>
                {
                  data.map((item) => {
                    return (
                      <div key={item.id} className={styles.contentImg} onClick={() => setId(item.id) } style={{ background: id == item.id ? '#e91e63' : '#f8f8f8' }}>
                        <img src={id == item.id ? item.src_w : item.src } style={{ width: '100%', height: '100%'}} />
                      </div>
                    )
                  })
                }
              </div>
            </Form.Item>
            <Form.Item>
              <Button className={styles.btn} type='primary' onClick={handleOk}>开始授权</Button>
            </Form.Item>
          </Form>
          <BuyConfirm { ...BuyConfirmProps } />
        </div>
      </div>
    );
  } else {
    return <Navigate to={`/user/login`} />;
  }
};